package com.yhg.qxmall.cartorder.controller;

import java.util.Arrays;
import java.util.Map;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhg.qxmall.cartorder.service.FmsCartItemService;
import com.yhg.qxmall.cartorder.vo.CartItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.yhg.qxmall.cartorder.entity.FmsCartEntity;
import com.yhg.qxmall.cartorder.service.FmsCartService;
import com.yhg.common.utils.PageUtils;
import com.yhg.common.utils.R;



/**
 * 
 *
 * @author 凌月青缃
 * @email 13@qxmall.com
 * @date 2020-12-21 23:23:18
 */
@RestController
@RequestMapping("cartorder/cart")
public class FrontCartController {
    @Autowired
    private FmsCartService cartService;

    @Autowired
    FmsCartItemService cartItemService;

    /**
     * 添加入购物车
     * @param vo
     * @return
     */
    @PostMapping("/addToCart")
    public R addToCart(@RequestBody CartItemVo vo){
//        FmsCartEntity cartEntity = new FmsCartEntity();
        FmsCartEntity memberCart = cartService.getOne(new QueryWrapper<FmsCartEntity>().eq("member_id", vo.getMemberId()));

        Long cartId =null;
        if (memberCart==null){
//            该用户未创建购物车，将用户信息插入表中并创建购物车
            FmsCartEntity cartEntity = new FmsCartEntity();
            cartEntity.setMemberId(vo.getMemberId());
            cartEntity.setCartId(vo.getMemberId());
            cartService.save(cartEntity);

            cartId = cartEntity.getCartId();
            //判断是否存在个sku
//            cartItemService.addToCart(vo,cartId);
//            return R.ok().put("msg","存入购物车成功");
        }else {
            //用户信息已存在，直接进行操作
            cartId = memberCart.getCartId();
        }
            //判断是否存在个sku
            cartItemService.addToCart(vo,cartId);
            return R.ok().put("msg","存入购物车成功");

    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = cartService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		FmsCartEntity fmsCart = cartService.getById(id);

        return R.ok().put("fmsCart", fmsCart);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody FmsCartEntity fmsCart){
		cartService.save(fmsCart);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody FmsCartEntity fmsCart){
		cartService.updateById(fmsCart);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		cartService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
